import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:http/http.dart' as http;
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/assessment/assessmentDto.dart';
import 'package:ichinesereader/models/assessment/assessmentStudentQueryDto.dart';
import 'package:ichinesereader/models/assessment/assessmentTeacherQueryDto.dart';
import 'package:ichinesereader/models/class/ClassDetailsDto.dart';
import 'package:ichinesereader/models/class/announcementDto.dart';
import 'package:ichinesereader/models/common/usernameList.dart';
import 'package:ichinesereader/models/report/gradeComment.dart';
import 'package:ichinesereader/models/report/selfReadingDto.dart';
import 'package:ichinesereader/models/report/studentActivityDto.dart';
import 'package:ichinesereader/models/school/StudentToClassDto.dart';
import 'package:ichinesereader/models/school/moveClassStudentsDto.dart';
import 'package:ichinesereader/models/school/removeClassStudentDto.dart';
import 'package:ichinesereader/models/student/assignmentSearchDto.dart';
import 'package:ichinesereader/models/teacher/AssignmentType.dart';
import 'package:ichinesereader/models/teacher/assignmentDto.dart';
import 'package:ichinesereader/utils/commonApi.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/models/school/SchoolAdminProfileUpdateDto.dart';

class SchoolAdminServiceProvider extends GetConnect with CommonApi {
  SchoolAdminServiceProvider() {
    httpClient.addResponseModifier((request, response) {
      if (response.statusCode == 403) {
        Log.debug('${request.url} 403 error');
        if (!Get.isSnackbarOpen) {
          Get.snackbar(
            'Message'.tr,
            'You have been logged out due to inactivity or security reasons.'
                .tr,
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Color(0xff23c6c8),
            colorText: Color(0xffd8ffff),
          );
        }
        if (EasyLoading.isShow) EasyLoading.dismiss();
        if (Get.currentRoute != '/login') return Get.offAllNamed('/login');
      } else if (response.statusCode == 401) {
        Log.debug('${request.url} unauthorized access');
        try {
          // MessagePropertyResult mpr =
          //     messagePropertyResultFromJson(response.bodyString.toString());
          String message = response.bodyString.toString();
          if (message.contains('student not belong to class') ||
              message.contains(
                  'Selected student has been removed from the class')) {
            if (!Get.isSnackbarOpen) {
              Get.snackbar('Message'.tr,
                  'Selected student has been removed from the class'.tr,
                  backgroundColor: Color(0xff23c6c8),
                  colorText: Color(0xffd8ffff),
                  snackPosition: SnackPosition.BOTTOM);
            }
            //return Get.currentRoute;
          } else {
            if (!Get.isSnackbarOpen) {
              Get.snackbar('Message'.tr, 'Unauthorized access'.tr,
                  backgroundColor: Color(0xff23c6c8),
                  colorText: Color(0xffd8ffff),
                  snackPosition: SnackPosition.BOTTOM);
            }
            if (Get.currentRoute != '/login') {
              return Get.offAllNamed('/login');
            }
          }
        } catch (error) {
          if (!Get.isSnackbarOpen) {
            Get.snackbar('Message'.tr, 'Unauthorized access'.tr,
                backgroundColor: Color(0xff23c6c8),
                colorText: Color(0xffd8ffff),
                snackPosition: SnackPosition.BOTTOM);
          }
          if (Get.currentRoute != '/login') {
            return Get.offAllNamed('/login');
          }
        } finally {
          if (EasyLoading.isShow) EasyLoading.dismiss();
        }
      } else {
        Log.debug(response.request?.url.toString());
        return response;
      }
    });
    httpClient.maxAuthRetries = 2;
    httpClient.timeout = Duration(seconds: 30);
  }

////SchoolAdminProfile
  Future<dynamic> getSchoolAdminProfile() async {
    final box = Hive.box('appconfig');
    var _userName = box.get(CacheManagerKey['username'].toString());
    String url = '${Constants.BaseAPI}usermanager/getSchoolAdmin/$_userName';
    return commonApiGet(this, url, showFullLog: true);
  }

  Future<dynamic> updateSchoolAdminProfile(
      SchoolAdminProfileUpdateDto data) async {
    //SharedPreferences pref = await SharedPreferences.getInstance();
    //var _authtoken = pref.getString('AuthToken') ?? '';
    String url = '${Constants.BaseAPI}usermanager/updateschool';
    String jsonData = schoolAdminProfileUpdateDtoToJson(data);
    return commonApiPut(this, url, jsonData: jsonData, showFullLog: true);
  }

//////SchoolOverviewData
  Future<dynamic> getSchoolOverviewData() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    //Uri url = Uri.parse('${Constants.BaseAPI}schoolmanager/getSchoolOverview');
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getSchoolOverview',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

/////SchoolBasicStatics
  Future<dynamic> getSchoolBasicStatics() async {
    final box = Hive.box('appconfig');
    var sid = box.get('UserObjectId');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Uri url = Uri.parse(
    //     '${Constants.BaseAPI}schoolmanager/getStatisticData?schoolId=$sid');
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getStatisticData?schoolId=$sid',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

/////SchoolStaticList
  Future<dynamic> getSchoolStatisticList(
      String startTime, String endTime, bool isYear) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    var sid = box.get('UserObjectId');
    var datapoint = isYear ? "statistic_m" : "statistic_d";
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getStatisticList/$datapoint?schoolId=$sid&startTime=$startTime&endTime=$endTime',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

////SchoolActivities
  Future<dynamic> getSchoolActivities() async {
    final box = Hive.box('appconfig');
    var sid = box.get('UserObjectId');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getNewActivityList?schoolId=$sid',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

/////SchoolClasses
  Future<dynamic> getSchoolAllClassesDetails() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    //String url = '${Constants.BaseAPI}schoolmanager/getAllClassDetails';
    //return CommonApi.get(this, url, fullLog: true);
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getAllClassDetails',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getSchoolPrograms() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getSchoolProgram',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getSchoolClassesDetailsNewByClassId(String classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getClassInfos/$classId',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  ////add on Nov 18 for new class settings
  Future<dynamic> getClassSettingsByClassId(String classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getClassSettings/$classId',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

//{"status":1000,"message":"Congratulations, your class account has been created successfully ","result":null}
  Future<dynamic> createClass(ClassDetailsDto data) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Log.debug(classDetailsUpdateDtoToJson(data));
    final response = await post(
      '${Constants.BaseAPI}schoolmanager/createClass',
      classDetailsUpdateDtoToJson(data),
      headers: <String, String>{
        "authtoken": _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> updateClass(ClassDetailsDto data) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPI}schoolmanager/updateClass/${data.classId}',
      classDetailsUpdateDtoToJson(data),
      headers: <String, String>{
        "authtoken": _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//{"status":1000,"message":"your account has deleted successfully","result":null}
  Future<dynamic> removeClass(String classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await delete(
      '${Constants.BaseAPI}schoolmanager/deleteClass/$classId',
      headers: <String, String>{
        "authtoken": _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//返回classannouncementsresult结构
  Future<dynamic> getClassAnnouncementsByClassId(String classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/classannouncement/$classId?limit=0&page=0',
      headers: <String, String>{"authtoken": _authtoken},
      //body: assignmentSearchDtoToJson(searchDto),
    );
    return response;
  }

//返回List<Announcement>结构
  Future<dynamic> getStudentClassAnnouncementsByClassId(String classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/myclassannouncement/$classId',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  //返回Announcement结构
  Future<dynamic> getStudentReadAnnouncementsById(
      String classId, String announcementId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/myclassannouncement/$classId/$announcementId',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  //返回Announcement结构
  Future<dynamic> getClassAnnouncementDetailsById(
      String classId, String announcementId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/myclassannouncement/$classId/$announcementId',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

// 没有返回任何结果
  Future<dynamic> sendClassAnnouncement(
      String classId, ClassAnnouncementDto data) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPI}schoolmanager/classannouncement/$classId',
      classAnnouncementDtoToJson(data),
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

/////SchoolStudents
  Future<dynamic> getSchoolStudents(int page, int limit) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getAllStudentNew?page=$page&limit=$limit&sortField=class',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  /////SchoolStudents search
  Future<dynamic> searchSchoolStudents(String query) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getAllStudentNew?page=0&limit=0&query=$query&sortField=timestampCreated',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getStudentLevelProgress(String userName) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/progress/$userName',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  ////List<SchoolTeacher>
  Future<dynamic> getAllTeachersForASchool() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Uri url =
    //     Uri.parse('${Constants.BaseAPI}schoolmanager/getAllTeachersForASchool');
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getAllTeachersForASchool',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getClassOverviewTotalByClassId(
      String classId, String? startTime, String? endTime) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Uri url = Uri.parse(
    //     '${Constants.BaseAPI}superadmin/class/overview/total/$classId');
    String url = '${Constants.BaseAPI}superadmin/class/overview/total/$classId';
    if (startTime != null && endTime != null) {
      url += '?startTime=$startTime&endTime=$endTime';
    }
    final response = await get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> downloadAllClassReport() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url = '${Constants.BaseAPI}superadmin/class/overview/total/file';
    final response = await get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getClassOverviewLevelsByClassId(String classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Uri url = Uri.parse(
    //     '${Constants.BaseAPI}superadmin/class/overview/level/$classId');
    final response = await get(
      '${Constants.BaseAPI}superadmin/class/overview/level/$classId',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getClassStudentReportByClassId(
      String classId, String userName, AssignmentSearchDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Uri url = Uri.parse(
    //     '${Constants.BaseAPI}superadmin/class/overview/total/$classId');
    final response = await put(
      '${Constants.BaseAPI}superadmin/report/class/$classId/$userName',
      assignmentSearchDtoToJson(dto),
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getClassSkillsByClassId(
      String classId, bool firstAttempt) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url = '${Constants.BaseAPI}superadmin/skills/list/class/$classId';
    // Uri url =
    //     Uri.parse('${Constants.BaseAPI}superadmin/skills/list/class/$classId');
    if (firstAttempt)
      url =
          '${Constants.BaseAPI}superadmin/skills/list/class/$classId?firstFlag=true';
    // url = Uri.parse(
    //     '${Constants.BaseAPI}superadmin/skills/list/class/$classId?firstFlag=true');
    final response = await get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getClassOverviewDetailsByClassId(
      String classId, String? startTime, String? endTime) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Uri url = Uri.parse(
    //     '${Constants.BaseAPI}superadmin/class/overview/detail/$classId');
    String url =
        '${Constants.BaseAPI}superadmin/class/overview/detail/$classId';
    if (startTime != null && endTime != null) {
      url += '?startTime=$startTime&endTime=$endTime';
    }
    final response = await get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getClassAssignmentsByClassId(
      String classId, AssignmentSearchDto searchDto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Uri url =
    //     Uri.parse('${Constants.BaseAPI}schoolmanager/type/assignment/$classId');
    final response = await put(
      '${Constants.BaseAPI}schoolmanager/type/assignment/$classId',
      assignmentSearchDtoToJson(searchDto),
      headers: <String, String>{"authtoken": _authtoken},
      //body: assignmentSearchDtoToJson(searchDto),
    );
    return response;
  }

////List<AssignmentDetail>
  Future<dynamic> getAllAssignmentsByClass(
      String? classId, AssignmentType at) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Uri url =
    //     Uri.parse('${Constants.BaseAPI}schoolmanager/assignment/$classId');
    final response = await put(
      '${Constants.BaseAPI}schoolmanager/assignment/$classId',
      assignmentTypeToJson(at),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
      //body: assignmentTypeToJson(at),
    );
    return response;
  }

//返回结构较为复杂，所以用200来判定
  Future<dynamic> createAssignment(
      String cid, AssignmentDto dto, String? assignmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    if (assignmentId != '' && assignmentId != null) {
      // Edit Homework
      final response = await put(
        '${Constants.BaseAPI}schoolmanager/assignment/$cid/$assignmentId',
        assignmentDtoToJson(dto),
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        },
      );
      return response;
    } else {
      // create new one
      final response = await post(
        '${Constants.BaseAPI}schoolmanager/assignment/$cid',
        assignmentDtoToJson(dto),
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        },
      );
      return response;
    }
  }

  //返回空
  Future<dynamic> deleteAssignment(String cid, String assignmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await delete(
      '${Constants.BaseAPI}schoolmanager/assignment/$cid/$assignmentId',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> createAssessment(
      AssessmentDto dto, String? assessmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Log.debug(assessmentDtoToJson(dto));
    if (assessmentId != '' && assessmentId != null) {
      // edit
      final response = await put(
        '${Constants.BaseAPISuper}superadmin/assessment',
        assessmentDtoToJson(dto),
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        },
      );
      return response;
    } else {
      // create
      final response = await post(
        '${Constants.BaseAPISuper}superadmin/assessment',
        assessmentDtoToJson(dto),
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        },
      );
      return response;
    }
  }

//ParentLetterResult
  Future<dynamic> createParentLetters(UsernameList dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    var response;
    try {
      EasyLoading.show();
      response = await post(
        '${Constants.BaseAPI}schoolmanager/printhtml/parentletter',
        usernameListToJson(dto),
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        },
      );
    } catch (e) {
    } finally {
      EasyLoading.dismiss();
    }
    return response;
  }

  //ParentLetterResult
  Future<dynamic> createClassLoginCards(String classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    var response;
    try {
      EasyLoading.show();
      response = await get(
        '${Constants.BaseAPI}schoolmanager/printhtml/logincard/$classId',
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;',
        },
      );
    } catch (e) {
    } finally {
      EasyLoading.dismiss();
    }
    return response;
  }

  Future<dynamic> updateStudentIncentive(String username, bool disabled) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    var trueorfalse = disabled ? 'true' : 'false';
    final response = await put(
      '${Constants.BaseAPI}schoolmanager/toggleAllowInGame/$username/$trueorfalse',
      '',
      headers: <String, String>{
        "authtoken": _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> updateClassIncentive(String classId, bool disabled) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    var trueorfalse = disabled ? 'true' : 'false';
    final response = await put(
      '${Constants.BaseAPI}schoolmanager/toggleAllowInGameForClassStudent/$classId/$trueorfalse',
      '',
      headers: <String, String>{
        "authtoken": _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//assignment details
  Future<dynamic> getAssignmentDetailsByAssignmentId(
      String? classId, String? assignmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/myassignments/$classId/$assignmentId',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  // test new myassignments api for sudent
  Future<dynamic> getAssignmentDetailsByAssignmentIdNew(
      String? classId, String? assignmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/myassignmentsnew/$classId/$assignmentId',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//// getAllStudentsNotInGivenClass此api返回数据量较大，需要精简和优化
  ///返回 List<StudentDetails>
  ///2022.04.06使用新的api  getAllStudentsNotInClass
  Future<dynamic> getAllStudentsNotInGivenClass(String classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Uri url = Uri.parse(
    //     '${Constants.BaseAPI}schoolmanager/getAllStudentsNotInGivenClass/$classId');
    final response = await get(
      '${Constants.BaseAPI}schoolmanager/getAllStudentsNotInClass/$classId',
      headers: <String, String>{
        "authtoken": _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

////{"status":1000,"message":"Student(s) are assign to class successfully","result":null}
  Future<dynamic> addStudentsToClass(StudentToClassDto data) async {
    String url = '${Constants.BaseAPI}schoolmanager/addStudentsToClass';
    String jsonData = studentToClassDtoToJson(data);
    return commonApiPost(this, url, jsonData: jsonData, showFullLog: true);
  }

//// 这里的结构跟add不同，使用了classname，而不是class id
  ///return   []
  Future<http.Response> removeStudentsFromClass(
      String classId, RemoveClassStudentDto data) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Uri url = Uri.parse(
        '${Constants.BaseAPI}schoolmanager/removeStudentsFromClass/$classId');
    final response = await http.delete(
      url,
      headers: <String, String>{
        "authtoken": _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
      body: removeClassStudentDtoToJson(data),
    );
    Log.debug(response.request?.url.toString());
    return response;
  }

////{"status":1000,"message":"Successfully moved. ","result":null}
  Future<dynamic> moveClassStudents(MoveClassStudentsDto data) async {
    String url = '${Constants.BaseAPI}schoolmanager/moveclass';
    String jsonData = moveClassStudentsDtoToJson(data);
    return commonApiPost(this, url, jsonData: jsonData);
  }

  Future<dynamic> disableClassLeaderBoard(bool status) async {
    String url =
        '${Constants.BaseAPI}schoolmanager/school/settings/leaderboard/class/${status.toString()}';
    return commonApiPut(this, url);
  }

  Future<dynamic> disableWorldClassLeaderBoard(bool status) async {
    String url =
        '${Constants.BaseAPI}schoolmanager/school/settings/leaderboard/world/${status.toString()}';
    return commonApiPut(this, url);
  }

  Future<dynamic> getStudentStatics(String username) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url = '${Constants.BaseAPI}superadmin/student/stats/$username';
    final response = await get(
      url,
      headers: <String, String>{
        "authtoken": _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    //Log.debug(response.request?.url.toString());
    return response;
  }

  Future<dynamic> getStudentSkillsByUsername(
      String userName, String? endTime, bool? isFirstAttempt) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url = '${Constants.BaseAPI}superadmin/skills/list/player/$userName';
    if (endTime != null) {
      url += '?to=$endTime';
    }
    if (isFirstAttempt != null && isFirstAttempt) {
      if (endTime != null) {
        url += '&';
      } else {
        url += '?';
      }
      url += "firstFlag=true";
    }
    final response = await get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getStudentActivity(
      String classId, String userName, StudentActivityDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPI}superadmin/report/class/$classId/activity/$userName?limit=120&page=0&sortField=-when';
    final response = await post(
      url,
      studentActivityDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getStudentAssessmentRecords(
      String classId, AssessmentStudentQueryDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPISuper}superadmin/assessment/report/$classId';
    final response = await put(
      url,
      assessmentStudentQueryDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getReportBaskets(String? classId, List<String>? content,
      List<String?> status, String? limit, String? page) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    if (limit == null) limit = '0';
    if (page == null) page = '0';
    String url =
        '${Constants.BaseAPI}superadmin/basket/$classId?limit=$limit&page=$page&sortField=-when';
    final response = await post(
      url,
      jsonEncode({'content': content, 'status': status}),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> removeFromBasket(String classId, String id) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());

    String url = '${Constants.BaseAPI}superadmin/basket/$classId/$id';
    final response = await delete(
      url,
      headers: <String, String>{'authtoken': _authtoken, 'dataType': 'text'},
    );
    return response;
  }

  // type : writing    recording
  Future<dynamic> basketReview(
      String type, String userName, String bookId, String? assignmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    var gc = GradeComment(grade: '', comment: '');
    String url =
        '${Constants.BaseAPI}studentmanager/$type/review/$userName/$bookId';
    if (assignmentId != null && assignmentId != '') {
      url =
          '${Constants.BaseAPI}studentmanager/$type/review/$userName/$bookId/$assignmentId';
    }
    final response = await put(
      url,
      gradeCommentToJson(gc),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> downloadFileLocation(fileId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}studentmanager/location/file/$fileId',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8',
      },
    );
    return response;
  }

  Future<dynamic> basketGrade(String type, String userName, String bookId,
      String? assignmentId, String grade, String? comment) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    var gc = GradeComment(grade: grade, comment: comment ?? '');
    String url =
        '${Constants.BaseAPI}studentmanager/$type/grade/$userName/$bookId';
    if (assignmentId != null && assignmentId != '') {
      url =
          '${Constants.BaseAPI}studentmanager/$type/grade/$userName/$bookId/$assignmentId';
    }
    final response = await put(
      url,
      //jsonEncode({"grade": grade, "comment": comment}),
      gradeCommentToJson(gc),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8',
      },
    );
    return response;
  }

  Future<dynamic> getTeacherAssessmentRecords(
      String classId, AssessmentTeacherQueryDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPISuper}superadmin/assessment/report/$classId?sortField=-submittedTime';
    final response = await put(
      url,
      assessmentTeacherQueryDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> downloadGradeReport(String fileId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPISuper}superadmin/examination/report/file/$fileId';
    final response = await get(
      url,
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> getSignleAssignmentRecord(String classId, String id) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPI}superadmin/report/assignment/$classId/$id';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getAssignmentStudentReport(
      String assignmentId, String userName) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPI}superadmin/report/assignment/$assignmentId/student/$userName';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getAssignmentReportForUser(
      String classId, String assignmentId, String userName) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPI}superadmin/report/assignment/$classId/$assignmentId/$userName';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getSelfReading(String userName, SelfReadingDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPI}superadmin/selfreading/$userName?limit=200&page=0';
    final response = await post(
      url,
      selfReadingDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getMySelfReading(SelfReadingDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url = '${Constants.BaseAPI}superadmin/selfreading?limit=200&page=0';
    final response = await post(
      url,
      selfReadingDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getStudentQuizAttemp(String bookId, String userName) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPI}superadmin/student/quiz/attempts/$bookId/$userName';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getLibraryOverviewClassData(String classId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPISuper}superadmin/examination/library/overview/$classId';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getLibraryKnowledgeClassData(
      String classId, String level) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPISuper}superadmin/examination/library/knowledge/$classId/$level';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getLibraryKnowledgeUserData(String level) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPISuper}superadmin/examination/library/knowledge/$level';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getLibraryOverviewUserData() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPISuper}superadmin/examination/library/overview';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }
}
